<template>
    <div class="main coupon-edit">
        <section>
            <el-form  size="medium" ref="form" label-width="150px" :rules="commonRules"  :model="configData">
                <div class="block-header"><div>基础信息</div></div>
                <div class="block-content">
                   <el-form-item label="箱起奖金类型:" prop="boxBonusConfig.configType" :rules="commonRules.notNullRule"  >
                        <el-radio v-model="configData.boxBonusConfig.configType" :label="1" :disabled="type===2||type ===0" >售卖箱数</el-radio>
                        <el-radio v-model="configData.boxBonusConfig.configType" :label="0" :disabled="type===2||type ===0" >贡献点</el-radio>
                    </el-form-item>
                    <el-form-item label="奖金名称:" prop="boxBonusConfig.name"  :rules="commonRules.notNullRule">
                        <el-input v-model="configData.boxBonusConfig.name"  :disabled="type===2||type ===0" ></el-input>
                    </el-form-item>
                    <el-form-item label="有效期:"  prop="timeDate"  :rules="commonRules.notNullRule">
                        <template>
                            <el-date-picker 
                                :disabled="type===2 || (configData.boxBonusConfig.type===2 || configData.boxBonusConfig.type===3)"
                                v-model="configData.timeDate"
                                type="monthrange"
                                range-separator="至"
                                start-placeholder="开始月份"
                                end-placeholder="结束月份"
                                value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                            <span v-if="configData.boxBonusConfig.type===2||configData.boxBonusConfig.type===3" style="color:red;marginLeft:10px">该模型已配置奖金链接，修改有效期需先解除链接</span>
                        </template>
                    </el-form-item>
                    <!-- <el-form-item label="失效时间:"  prop="boxBonusConfig.endTime"   :rules="commonRules.notNullRule">
                        <template>
                            <el-date-picker
                                :disabled="type===2"
                                v-model="configData.boxBonusConfig.endTime"
                                type="month"
                                value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </template>
                    </el-form-item> -->
                    <el-form-item label="选择箱起活动:" :rules="commonRules.notNullRule">
                        <div class="add-btn-block">
                            <el-button type="primary" size="small" icon="el-icon-circle-plus"  plain @click="addBox" :disabled="type===2">添加箱起活动</el-button>
                        </div>
                    </el-form-item> 
                </div>
                <el-table :data="configData.boxSeriesDTOs"  :default-expand-all="true" ref="expandTable">
                    <el-table-column align="center" type="expand" width="100px">
                        <template slot-scope="scope">
                            <el-table :data="scope.row.boxGoodsDTOS" >
                                <el-table-column align="center" label="商品名称" prop="goodsName"></el-table-column>
                                <el-table-column align="center" label="起卖数量" prop="minnum" ></el-table-column>
                                <el-table-column align="center" label="箱规（件）" prop="boxCount" ></el-table-column>
                                <el-table-column align="center" label="普通会员价" prop="ordinaryPrice" ></el-table-column>
                                <el-table-column align="center" label="大区价" prop="regionPrice"></el-table-column>
                                <el-table-column align="center" label="董事价" prop="directorPrice" ></el-table-column>
                                <el-table-column align="center" label="销售贡献点比" v-if="configData.boxBonusConfig.configType===0" width="250px">
                                    <template slot-scope="$scope">
                                         <span style="float:left">
                                            <el-form-item label-width="0" :prop="`boxSeriesDTOs[${scope.$index}].boxGoodsDTOS[${$scope.$index}].pointBefore`"  :rules="{required: true, message: '不能为空', trigger: 'change'}" >
                                                <el-input type="number" v-model="$scope.row.pointBefore" style="width:100px" :disabled="type===2||type ===0"></el-input>
                                            </el-form-item>
                                        </span>
                                        <span style="margin: 10px 10px 0;float:left">:</span>
                                        <span style="float:left">
                                            <el-form-item label-width="0" :prop="`boxSeriesDTOs[${scope.$index}].boxGoodsDTOS[${$scope.$index}].pointAfter`"  :rules="{required: true, message: '不能为空', trigger: 'change'}" >
                                                <el-input type="number" v-model="$scope.row.pointAfter" style="width:100px" :disabled="type===2||type ===0"></el-input>
                                            </el-form-item>
                                        </span>
                                    </template>
                                </el-table-column>    
                            </el-table>
                        </template> 
                    </el-table-column>
                    <el-table-column label="活动名称" prop="seriesName" align="center"></el-table-column>
                    <el-table-column align="center" label="操作" width="60" fixed="right">
                        <template slot-scope="scope">
                            <a href="javascript: void(0);" class="el-icon-remove" @click="delBoxSeriesDTOs(scope.$index, scope.row.seriesId)"></a>
                        </template>
                    </el-table-column>
                </el-table>    
            </el-form>
            <div class="block-header"><div>奖金阶梯{{configData.boxBonusConfig.configType===1?'（售卖箱数)':'(贡献点)'}}</div></div>
            <div style="margin-bottom:10px;" v-if="!id&&configData.boxBonusConfig.configType===1">
                <el-upload
                    :show-file-list="false"
                    :action="bonusUpload"
                    name="file"
                    :on-success="(res)=>uploadSucceed(res)"
                    :on-error ="(err) => uploadErr(err)"
                    >
                    <el-button size="small" type="primary">一键导入</el-button>
                </el-upload>
            </div>
            <el-form :model="customData" :rule="commonRules" ref="form1">     
                <div class="section-content" v-if="configData.boxBonusConfig.configType===1" >   
                    <el-form-item v-for="(rule, index) in customData.boxRules" :key="index" :label="`规则${index+1}：`" required >
                        <el-row align="center">
                            <el-col :md="4" :xl="4">
                                <el-form-item :prop="`boxRules[${index}].minUnit`" :rules="commonRules.numberRule">
                                    <el-input type="number" v-model="rule.minUnit" :disabled="type===2||type ===0">
                                        <template slot="prepend">最小单位（箱）</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col class="line" :span="1">-</el-col>
                            <el-col :md="4" :xl="4">
                                <el-form-item :prop="`boxRules[${index}].maxUnit`" :rules="commonRules.numberRule">
                                    <el-input type="number" v-model="rule.maxUnit"  :disabled="type===2||type ===0">
                                        <template slot="prepend">最高单位（箱）</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :offset="1" :md="4" :xl="3">
                                <el-form-item :prop="`boxRules[${index}].boxRate`" :rules="commonRules.priceRule">
                                    <el-input type="number" v-model="rule.boxRate" :disabled="type===2||type ===0">
                                        <template slot="prepend">单箱系数</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :offset="1" :md="4" :xl="3">
                                <el-form-item  :prop="`boxRules[${index}].bonusPrice`" :rules="commonRules.priceRule">
                                    <el-input type="number" v-model="rule.bonusPrice" :disabled="type===2||type ===0">
                                        <template slot="prepend">单箱奖金</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :offset="1" :md="4" :xl="3" >
                                <el-button v-if="!index" type="success" size="small" icon="el-icon-circle-plus" plain @click="addBoxRule" :disabled="type===2||type ===0">添加规则</el-button>
                                <el-button v-if="index" type="danger" size="small" icon="el-icon-remove" plain @click="delBoxRule(index)" :disabled="type===2||type ===0">移除规则</el-button> 
                            </el-col>
                        </el-row>
                    </el-form-item>   
                </div>
                <div class="section-content" v-if="configData.boxBonusConfig.configType===0">
                    <el-form-item v-for="(rule, index) in customData.contributionRules" :key="index" :label="`规则${index+1}：`" required>
                        <el-row align="center">
                            <el-col :md="4" :xl="4">
                                <el-form-item :prop="`contributionRules[${index}].minUnit`" :rules="commonRules.priceRule">
                                    <el-input type="number" v-model="rule.minUnit" :max="rule.minUnit" :disabled="type===2||type ===0">
                                         	<template slot="prepend">最小单位（贡献点）</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col class="line" :span="1">-</el-col>
                            <el-col :md="4" :xl="4">
                                <el-form-item  :prop="`contributionRules[${index}].maxUnit`" :rules="commonRules.priceRule">
                                    <el-input type="number" v-model="rule.maxUnit" :min="rule.maxUnit"  :disabled="type===2||type ===0">
                                        <template slot="prepend">最高单位（贡献点）</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :offset="1" :md="4" :xl="3">
                                <el-form-item :prop="`contributionRules[${index}].boxRate`" :rules="commonRules.priceRule">
                                    <el-input type="number" v-model="rule.boxRate"  :disabled="type===2||type ===0">
                                        <template slot="prepend">贡献点系数</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :offset="1" :md="4" :xl="3">
                                <el-form-item :prop="`contributionRules[${index}].bonusPrice`" :rules="commonRules.priceRule">
                                    <el-input type="number" v-model="rule.bonusPrice" :disabled="type===2||type ===0" >
                                        <template slot="prepend">贡献点奖金</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :offset="1" :md="4" :xl="3" >
                                <el-button v-if="!index" type="success" size="small" icon="el-icon-circle-plus" plain @click="addContributionRules" :disabled="type===2||type ===0" >添加规则</el-button>
                                <el-button v-if="index" type="danger" size="small" icon="el-icon-remove" plain @click="delContributionRules(index)" :disabled="type===2||type ===0" >移除规则</el-button>
                            </el-col>
                        </el-row>
                    </el-form-item>
                </div>  
                <el-form-item label="">
                    <el-button type="primary" size="medium" :loading="btnLoading" @click="save" v-show="type!==2" >保存</el-button>
                    <el-button type="info" size="medium" plain @click="$router.push({ name: 'boxBonus' })">{{ type===1||type ===0 ? '取消':'返回'}}</el-button>
                </el-form-item> 
            </el-form>
        </section>
    </div>
</template>
<script>
  export default {
    name: 'boxBonusEdit',
    mounted(){
        this.id = this.$route.query.id
        this.type = Number(this.$route.query.type)
        if(this.id) {
            this.getConfig()
        } else {
            this.customData.boxRules.push({
                bonusPrice: '',
                boxRate: '',
                detailType: 1,
                maxUnit: '',
                minUnit: ''
            })
            this.customData.contributionRules.push({
                bonusPrice: '',
                boxRate: '',
                detailType: 0,
                maxUnit: '',
                minUnit: ''
            })
        }
    },
    data(){
        return {
            configData:{
                timeDate: [],
                boxBonusConfig: {
                    bonusConfigId: "",
                    configType: 1,
                    endTime: "",
                    name: "",
                    startTime: ""
                },
                boxBonusConfigDetails: [],
                boxSeriesDTOs: []
            },
            seriesName:'',
            boxSeriesDTOs:[],
            hasBoxSeriesDTOs: [],
            startTime:'',
            endTime:'',
            customData:{
                boxRules:[],
                contributionRules:[]
            },
            btnLoading: false,
            id: '',
            type: ''
        }
    },
    methods: {
        getConfig(){
            this.request({
            url: '/bsnl-product/box/bonus/config/detail?bonusConfigId='+this.id,
            method: 'get',
            }).then((res) => {
                if(res.status===200) {
                    this.configData = {
                        ...res.data,
                        timeDate: [res.data.boxBonusConfig.startTime, res.data.boxBonusConfig.endTime]
                    }
                    this.hasBoxSeriesDTOs = res.data.boxSeriesDTOs
                    if(this.configData.boxBonusConfigDetails.length>0){
                        for(var i=0;i<this.configData.boxBonusConfigDetails.length;i++) {
                            if(this.configData.boxBonusConfigDetails[i].detailType===1){
                                this.customData.boxRules.push(this.configData.boxBonusConfigDetails[i])
                            } else {
                                this.customData.contributionRules.push(this.configData.boxBonusConfigDetails[i])
                            }
                        }
                    }
                    if(this.customData.boxRules.length < 1){
                        this.customData.boxRules.push({
                            bonusPrice: '',
                            boxRate: '',
                            detailType: 1,
                            maxUnit: '',
                            minUnit: ''
                        })
                    }
                    if(this.customData.contributionRules.length < 1){
                        this.customData.contributionRules.push({
                            bonusPrice: '',
                            boxRate: '',
                            detailType: 0,
                            maxUnit: '',
                            minUnit: ''
                        })
                    }
                }
            }).catch(err => {
               this.$message.success(err.message)
            });
        },
        addBox(){ 
            this.boxSeriesDTOs = [...this.configData.boxSeriesDTOs]
            this.boxSeries(this.boxSeriesDTOs, -1, 2, this.hasBoxSeriesDTOs).then(val => {
            this.configData.boxSeriesDTOs = val
            }).catch(err => {
             this.boxSeriesDTOs=[]
            });
        },
        delBoxSeriesDTOs(index, id){
            if(this.type===2||this.type===0){
                this.type===0 && this.$message.error('之前添加的箱起活动不支持删除')
                return
            } else {
                this.configData.boxSeriesDTOs
                var aa = true
                this.hasBoxSeriesDTOs.forEach((item) => {
                    if(item.seriesId === id) {
                       aa = false
                    }
                })
                if(aa) {
                    this.configData.boxSeriesDTOs.splice(index, 1)
                } else {
                    this.$message.error('之前添加的箱起活动不支持删除')
                    return false
                }   
            } 
        },
        addBoxRule() {
            this.customData.boxRules.push({
                bonusPrice: '',
                boxRate: '',
                detailType: 1,
                maxUnit: '',
                minUnit: ''
            })
        },
        delBoxRule(index) {
            this.customData.boxRules.splice(index, 1)
        },
        addContributionRules() {
            this.customData.contributionRules.push({
                bonusPrice: '',
                boxRate: '',
                detailType: 0,
                maxUnit: '',
                minUnit: ''
            })
        },
        delContributionRules(index) {
            this.customData.contributionRules.splice(index, 1)
        },
        save() {
            if(this.configData.boxSeriesDTOs.length<1) {
                this.$message.error('请添加箱起活动')
                return false
            }
            if(this.configData.boxBonusConfig.configType===0) {
                for(var i=0;i<this.configData.boxSeriesDTOs.length;i++) {
                    for(var j=0;j<this.configData.boxSeriesDTOs[i].boxGoodsDTOS.length;j++) {
                        if(!this.configData.boxSeriesDTOs[i].boxGoodsDTOS[j].pointAfter||!this.configData.boxSeriesDTOs[i].boxGoodsDTOS[j].pointBefore) {
                            this.toggleRowExpansion(this.configData.boxSeriesDTOs[i])
                            this.$message.error('请填写销售贡献点比')
                            return false
                        }
                    }
                }
            }
            
            this.$refs.form.validate(valid => {
                if(valid) {
                    this.$refs.form1.validate(valid1 => {
                        if(valid1) {
                             this.btnLoading=true
                            if(this.configData.boxBonusConfig.configType===1) {
                                this.configData.boxBonusConfigDetails = this.customData.boxRules
                            } else {
                                this.configData.boxBonusConfigDetails = this.customData.contributionRules
                            }
                            var endMonth = this.formatDate(this.configData.timeDate[1], 'YYYY-MM')
                            var endDate = new Date(endMonth)
                            var month=endDate.getMonth()
                            var nextMonth=++month
                            var nextMonthFirstDay=new Date(endDate.getFullYear(), nextMonth, 1)
                            var oneDay=1000*60*60*24
                            var dateString=new Date(nextMonthFirstDay-oneDay).toLocaleDateString()
                            var endTime = dateString.replace(new RegExp('/', 'g'), "-")
                            this.configData.boxBonusConfig.startTime = this.configData.timeDate[0]
                            this.configData.boxBonusConfig.endTime = this.formatDate(endTime, 'YYYY-MM-DD') +' 23:59:59'
                            let bonusUrl = this.id ? '/bsnl-product/box/bonus/config/update':'/bsnl-product/box/bonus/config/add'
                            this.request({
                                url: bonusUrl,
                                method: 'post',
                                data:this.configData
                            }).then((res) => {
                                if(res.status===200) {
                                    this.$message.success(res.message)
                                    this.btnLoading=false
                                    this.$router.push({ name: 'boxBonus' })
                                }
                            }).catch((err)=> {
                                this.btnLoading=false
                            })
                        }
                    })  
                }     
            })
        },
        toggleRowExpansion(row) {
           this.$refs.expandTable.toggleRowExpansion(row, true) 
        },
        uploadSucceed(res) {
            var arr = res.data
            this.customData.boxRules= []
            arr.forEach((item) =>{
                this.customData.boxRules.push({
                    bonusPrice: item.bonusPrice,
                    boxRate: item.boxRate,
                    detailType: 1,
                    maxUnit: item.maxUnit,
                    minUnit: item.minUnit
                })
            })
        },
        uploadErr(err) {
            this.$message.error(err.message)
        }
    }   
  }
</script>
<style lang="scss">
    @import "../../../styles/_mixin.scss";
    .block-header{
        color: #1ea0ff;
        font-size: 14px;
        padding: 12px 0;
        margin-bottom: 12px;
        background: #f7f7f7;
        &>div{
            padding: 0 12px;
            border-left: 2px solid #1ea0ff;
        }
    }

    .coupon-edit .el-form .el-textarea .el-textarea__inner{
        height: auto;
    }
    .adviceTxt{
        color: #8c939d
    }
    .use-type-block{
        @include flex;
        margin-left: 24px;
    }
    .add-btn-block{
        margin:  0 0 12px 24px;
    }
     .section-content{
         .el-input-group__prepend{
             padding: 0 5px;
         }
        .line{
            text-align: center;
        }
        .el-input{
            width: 100%;
            max-width: 500px;
            min-width: 150px;
        }
        .el-icon-delete{
            color: red;
            font-size: 16px;
            margin: 0 12px;
            cursor: pointer;
        }
        .goods-item{
            padding: 12px 0;
            // border: 1px solid #efefef;
            border-radius: 6px;
            position: relative;

            .avatar-uploader .el-upload,
            .upload-img-list li,
            .upload-img-list .upload-btn{
                width: 120px;
                height: 120px;
                line-height: 118px;
            }
            .upload-img-list .img-preview .img-preview-mask .mask-btn {
                margin-top: 47px;
                line-height: 36px;
                text-align: center;
            }

            .present-item{
                padding: 6px;
                border: 1px solid #efefef;
                margin-bottom: 12px;
                position: relative;

                .el-icon-error{
                    color: red;
                    font-size: 18px;
                    cursor: pointer;
                    top: 12px;
                    right: 12px;
                    position: absolute;
                    z-index: 9;
                }

                &>.el-form-item {
                    margin-bottom: 22px;
                }
                .el-input,
                .el-select{
                    width: 100%;
                    max-width: 160px;
                }
            }
        }
        .add-btn-block{
            margin:  0 0 12px 24px;
        }
        .footer-block{
            text-align: center;
            margin-top: 24px;
        }
    }
</style>
